import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';

import { WarehouseGoodsService } from './warehouse-goods.service';
import {PermissionService} from '../../../service/permission.service';

@Component({
    selector: 'app-warehouse-goods',
    templateUrl: './warehouse-goods.component.html',
    styleUrls: ['./warehouse-goods.component.scss']
})
export class WarehouseGoodsComponent implements OnInit {

    isCollapse: boolean = false;
    /**
     * 列表数据源
     */
    listOfData?: any;
    /**
     * 查询load动画
     */
    isLoadingOne = false;
    /**
     * 当前是否在搜索
     */
    searchHint = false;
    /**
     * 商品分类下拉
     */
    GoodsTypeList: any = [];
    /**
     * 品牌下拉
     */
    BrandList: any = null;
    /**
     * 当前搜索name
     */
    searchName = "";
    /**
     * 表单load动画
     */
    tableLoading: boolean = false;
    /**
     * 加载失败显示图像占位符
     */
    fallback =
        '';
    /**
     * 查询参数
     */
    queryForm: any = {
        // 商品名称
        name: '',
        // 商品分类
        type: '',
        // 品牌ID
        brandId: '',
        // 属性
        attr: '',
        // 开始时间
        beginTime: '',
        // 结束时间
        endTime: '',
        // 时间区间
        dateFormat: [],
        // 69码
        code: '',
        page: '1',
        pageSize: '20',
        // 0 默认方式   1实际库存  2不良品库存
        whGoodsSort: 0,
        // true 正序  false 倒序
        asc: true
    }
    /**
     * 全局 loading
     */
    messageId: any = null;
    /**
     * 路由缓存恢复时
     */
    static updateCache: any = null;

    cacheData: any = {
        brandIdList: [],
        typeList: []
    }
    constructor(
        private warehouseGoodsService: WarehouseGoodsService,
        private message: NzMessageService,
        public permission: PermissionService,
    ) { }

    ngOnInit() {
        WarehouseGoodsComponent.updateCache = () => {
            this.tableLoading = false;
            this.getGoodsList();
            this.getBrandList();
            this.getGoodsTypeList();
        }
        this.getGoodsList();
        this.getBrandList();
        this.getGoodsTypeList();
    }
    /**
     * 查询
    */
    query() {
        this.queryForm.whGoodsSort = 0
        this.queryForm.asc = true

        this.queryForm.page = 1;
        this.getGoodsList();
    }
    // 重置
    resetTable() {
        this.queryForm.name = '';
        this.queryForm.code = '';
        this.queryForm.attr = '';
        this.cacheData.brandIdList = [];
        this.queryForm.brandId = '';
        this.cacheData.typeList = [];
        this.queryForm.type = '';
        this.queryForm.dateFormat = [];
        this.queryForm.beginTime = '';
        this.queryForm.endTime = '';
        
        this.queryForm.page = 1;
        this.getGoodsList();
    }
    /**
     * 搜索返回原列表
    */
    backList() {
        this.queryForm.name = "";
        this.queryForm.type = "";
        this.queryForm.brandId = "";
        this.queryForm.code = "";
        this.queryForm.attr = "";
        this.queryForm.dateFormat = [];
        this.queryForm.beginTime = "";
        this.queryForm.endTime = "";
        this.queryForm.page = 1;
        this.searchHint = false;
        this.getGoodsList();
    }
    /**
     * 页码改变
     * @param index 页码数
     */
    onPageIndexChange(index: Number) {
        // console.log(index);
        this.queryForm.page = index;
        this.getGoodsList();
    }
    /**
     * 每页条数改变的回调
     * @param index 页码数
     */
    onPageSizeChange(index: Number) {
        this.queryForm.pageSize = index;
        this.getGoodsList();
        // console.log(index);
    }
    /**
     * 同步
     */
    synchro() {
        if (this.messageId != null) {
            return;
        }
        this.createBasicMessage();
        this.warehouseGoodsService.itemSynchronize().subscribe((res: any) => {
            this.removeBasicMessage();
            if (res.code != 0) {
                this.createMessage("error", res.message);
                return;
            }
            this.createMessage("success", res.data);
        }, err => {
            this.removeBasicMessage();
            this.createMessage("error", err.message);
        })
    }
    /**
     * 同步商品库存
     */
    synchroStore() {
        if (this.messageId != null) {
            return;
        }
        this.createBasicMessage();
        this.warehouseGoodsService.stockInventoryQuery().subscribe((res: any) => {
            this.removeBasicMessage();
            if (res.code != 0) {
                this.createMessage("error", res.message);
                return;
            }
            this.createMessage("success", "同步商品库存成功");
        }, err => {
            this.removeBasicMessage();
            this.createMessage("error", err.message);
        })
    }
    getGoodsList() {
        if (this.tableLoading) { return; }
        this.listOfData = [];
        this.tableLoading = true;

        this.warehouseGoodsService.getList(this.queryForm).subscribe((res: any) => {
            this.listOfData = res.data;

            let textArr = [];
            if (this.queryForm.name) {
                textArr.push(this.queryForm.name);
            }
            if (this.queryForm.code) {
                textArr.push(this.queryForm.code);
            }
            if (this.queryForm.attr) {
                textArr.push(this.queryForm.attr);
            }
            if (this.queryForm.brandId) {
                textArr.push(this.queryForm.brandId);
            }
            if (this.queryForm.type) {
                textArr.push(this.queryForm.type);
            }
            if (this.queryForm.dateFormat) {
                textArr.push(this.queryForm.dateFormat);
            }
            this.searchName = textArr.join(' | ');

            this.isLoadingOne = false;

            for (let index = 0; index < this.listOfData?.records?.length; index++) {
                const element = this.listOfData.records[index];
                element.stateText = this.state_To_text(element.state);
            }
            this.tableLoading = false;
        }, err => {
            this.tableLoading = false;
        })
    }

    /**
     * 商品分类下拉
     */
    getGoodsTypeList() {
        this.warehouseGoodsService.getGoodsTypeList().subscribe((res: any) => {
            if (res.code != 0) {
                this.createMessage("error", res.message);
                return;
            }
            // this.GoodsTypeList = res.data;
            this.GoodsTypeList = this.addFieldArr(res.data);
        }, err => {
            this.createMessage("error", "请求失败");

        })
    }
    /**
     * 商品 品牌下拉
     */
    getBrandList() {
        this.warehouseGoodsService.getBrandList().subscribe((res: any) => {
            if (res.code != 0) {
                this.createMessage("error", res.message);
                return;
            }
            this.BrandList = res.data;
        }, err => {

        })
    }

    // 品牌 全选
    onSelectBrandAll(ev: any) {
        if (ev.includes('all')) {
            this.cacheData.brandIdList = []
            this.BrandList.forEach((element: any) => {
                const { id } = element
                if (id) {
                    this.cacheData.brandIdList.push(`${id}`)
                }
            });
        }
        this.queryForm.brandId = this.cacheData.brandIdList.join(',')
    }
    // 类型 全选
    onSelectTypeAll(ev: any) {
        if (ev.includes('all')) {
            this.cacheData.typeList = []
            this.GoodsTypeList.forEach((element: any) => {
                const { id } = element
                if (id) {
                    this.cacheData.typeList.push(`${id}`)
                }
            });
        }
        this.queryForm.type = this.cacheData.typeList.join(',')
    }

    // 0 默认方式   1实际库存  2不良品库存
    // asc true-升序排序、false-降序排序
    onTableFilter(val: any) {
        this.queryForm.whGoodsSort = val
        this.queryForm.asc = !this.queryForm.asc
        this.getGoodsList();
    }

    /**
     * 确认删除
     * @param id
     */
    confirm(id: any = null) {
        if (this.messageId != null) {
            return;
        }

        this.createBasicMessage();
        this.warehouseGoodsService.del({ id: id }).subscribe((res: any) => {
            this.removeBasicMessage();
            if (res.code != 0) {
                this.createMessage("error", res.message);
                return;
            }
            this.createMessage("success", "删除成功");
            this.getGoodsList();
        }, err => {
            this.isLoadingOne = false;
            this.removeBasicMessage();
            this.createMessage("error", err.message);
        });
    }
    /**
     * 状态转文字
     * @param state
    */
    state_To_text(state: any) {
        let text = "";
        switch (state) {
            case 0:
                text = "草稿";
                break;
            case 1:
                text = "待审核";
                break;
            case 2:
                text = "审核通过";
                break;
            case 3:
                text = "审核不通过";
                break;
            default:
                text = "-";
                break;
        }
        return text;
    }

    // 分类下拉数据处理
    addFieldArr(arr: any) {
        return arr.map((item: any) => {
            if (item.children && item.children.length > 0) {
                // item.disabled = true;
                item.children = this.addFieldArr(item.children);
            }

            if (item.children && item.children.length == 0) {
                item.isLeaf = true;
            }

            let obj: any = {
                ...item,
                key: item.id,
                title: item.name
            }
            return obj
        })
    }
    // 分类选择
    onChangeTree(event: any) {
        // console.log('selected type', event);
        if (event) {
            // this.queryForm.type = this.cacheData.typeList.join(',');
            this.queryForm.type = this.cacheData.typeList;
        }
    }
    /**
     * 开启loading
     */
    createBasicMessage(): void {
        this.messageId = this.message.loading('正在请求...', { nzDuration: 0 }).messageId;
    }
    /**
     * 移除loading
     */
    removeBasicMessage() {
        this.message.remove(this.messageId);
        this.messageId = null;
    }
    /**
    * 全局展示操作反馈信息
    * @param type 其他提示类型 success:成功 error:失败 warning:警告
    */
    createMessage(type: any, str: any): void {
        this.message.create(type, str);
    }
}
